<?php
namespace app\a\controller;
use app\BaseController;
use think\facade\Db;
use qiniu\Qn;
use think\facade\Cache;
use think\captcha\facade\Captcha;
class Login extends Base{
    //生成验证码
    public function verify(){
        $id=mt_rand(100000, 999999);//验证码标识
        $uniqid = uniqid("$id");
        //返回数据 验证码图片路径、验证码标识
        $data = [
            'src' =>captcha_src($uniqid),
            'uniqid' => $uniqid
        ];
        return json($data);
    }

    // 登录后台
    public function loginAdmin(){
        $pt = input("post.");
        $captcha = new Captcha();
        if($captcha::check($pt['code'])){

            $res = $this->getResult(1,3);
            if (empty($res)) {
                $this->info['code']=201;
                $this->info['msg']='请求太快，请3秒之后再试';
                return json($this->info);
            }

            $where = [
                'user'=>trim($pt['user']),
                'pass'=>md5('anan'.md5(trim($pt['pass'])))
            ];
            $adminData = Db::table('an_admin')
            ->where($where)
            ->field('id,name,user,login_time,role_id')
            ->select()
            ->toArray(); 
            if(count($adminData) > 0){
                $this->logData('登录系统',$adminData[0]['id']);
                Db::table('an_admin')->where('id', $adminData[0]['id'])->data(['login_time'=>time()])->update();
                $this->info['code'] = 200;
                $this->info['msg'] = '登录成功';
                $this->info['token'] = signToken($adminData[0]['id']);
                $this->info['data'] = $adminData[0];
                return json($this->info);
            }else{
                $this->info['code'] = 201;
                $this->info['msg'] = '账号或密码有误';
                return json($this->info);
            }
        }else{
            $this->info['code'] = 201;
            $this->info['msg'] = '验证码有误';
            return json($this->info);
        }
    }

    /**
     * 使用jwt生成token字符串
     */
    public function getToken(){
        //从header里获取token
        $token= request()->header('token');

        //检查token
        $result = checkToken($token);

        $this->info['code'] = 201;
        $this->info['data'] = signToken($result['data']['uid']);
        return json($this->info);
    }

    /**
     * 使用jwt验证token字符串
     */
    public function checkJwtToken()
    {
        $token  = input('token'); // 接收生成token字符串
        $result = checkToken($token);
        // Array ( [status] => 200 [data] => Array ( [uid] => 123 ) )
        dump($result);
    }

}
